from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import uvicorn


class UnicornException(Exception):
    def __init__(self, name: str):
        self.name = name


class AppException(Exception):
    def __init__(self, name: str):
        self.name = name


app = FastAPI()

@app.exception_handler(Exception)
async def unicorn_exception_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={"message": f"server error"},
    )


@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
    return JSONResponse(
        status_code=418,
        content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
    )


@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
    if name == "yolo":
        raise UnicornException(name=name)
    if name == "test":
        raise Exception("test")
    if name == "app":
        raise AppException("app")
    return {"unicorn_name": name}


if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000)